<?php


namespace app\controller\admin;


use app\model\user\PartnerMoneyRecordModel;
use app\model\user\UserModel;
use app\model\user\UserMoneyDetailModel;
use app\service\user\PartnerMoneyRecordService;
use app\service\user\UserMoneyDetailService;
use app\service\utils\GenerateUserNickService;

class UserController extends BaseAdminController
{

    function setModel()
    {
        return new UserModel();
    }

    function setWithModel()
    {
        return [];
    }

    function setSearch()
    {
        return [
            'like' => ['username', 'mobile'],
            '=' => ['type'],
            'betweenTimestamp' => ['create_time']
        ];
    }

    function setSort()
    {
        // TODO: Implement setSort() method.
    }

    public function getList()
    {
        try {
            $list = parent::getList()->toArray();
            foreach ($list['data'] as $k => $v) {
                // 分享次数
                $shareNum = UserModel::where('pid', $v['id'])->count();
                $list['data'][$k]['shareNum'] = $shareNum;
                // 分享收入
                $shareAmount = UserMoneyDetailModel::where('user_id', $v['id'])
                    ->where('type', UserMoneyDetailService::INVITE_USER_BUY)
                    ->sum('amount');
                $list['data'][$k]['shareAmount'] = $shareAmount;
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    public function save()
    {
        try {
            $data = $this->request->except(['create_time']);
            if (!$data['id']) {
                if ($this->getModel()->where('mobile', $data['mobile'])->find()) {
                    throw new \Exception('账号已存在');
                }
                $data['nick'] = $data['nick'] ?: GenerateUserNickService::generateUserNick();
                $this->setModel()->save($data);
            } else {
                $model = $this->setModel()->find($data['id']);
                if ($data['mobile'] != $model['mobile'] && $this->getModel()->where('mobile', $data['mobile'])->find()) {
                    throw new \Exception('账号已存在');
                }
                $model->save($data);
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}